package com.demo2.todo.service.impl;

import com.demo2.todo.service.ShareReviewService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.demo2.todo.model.dto.ShareReviewRequest;
import com.demo2.todo.model.dto.ShareReviewResponse;
import com.demo2.todo.model.entity.ShareTodo;
import com.demo2.todo.model.entity.Todo;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.model.entity.SensitiveWord;
import com.demo2.todo.repository.ShareTodoRepository;
import com.demo2.todo.repository.TodoRepository;
import com.demo2.todo.repository.UserRepository;
import com.demo2.todo.repository.SensitiveWordRepository;
import lombok.RequiredArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author evi
 */
@Service
@RequiredArgsConstructor
public class ShareReviewServiceImpl implements ShareReviewService {

    private final ShareTodoRepository shareTodoRepository;
    private final TodoRepository todoRepository;
    private final UserRepository userRepository;
    private final SensitiveWordRepository sensitiveWordRepository;

    @Override
    @Transactional(readOnly = true)
    public List<ShareReviewResponse> getPendingReviews() {
        // 获取所有待审核的分享记录
        List<ShareTodo> pendingShares = shareTodoRepository
                .findByReviewStatusOrderByCreatedAtAsc(ShareTodo.ReviewStatus.pending);

        return pendingShares.stream()
                .map(this::convertToReviewResponse)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ShareReviewResponse reviewShare(Long shareId, ShareReviewRequest request, User admin) {
        ShareTodo shareTodo = shareTodoRepository.findById(shareId)
                .orElseThrow(() -> new RuntimeException("分享记录不存在"));

        // 检查是否已审核
        if (shareTodo.getReviewStatus() != ShareTodo.ReviewStatus.pending) {
            throw new RuntimeException("该分享已审核，不能重复处理");
        }

        // 更新审核状态
        shareTodo.setReviewStatus(ShareTodo.ReviewStatus.valueOf(request.getReviewStatus()));
        shareTodo.setReviewedBy(admin.getId());
        shareTodo.setReviewedAt(LocalDateTime.now());
        shareTodo.setReviewComment(request.getReviewComment());

        // 如果审核通过，设置为公开
        if (ShareTodo.ReviewStatus.approved.name().equals(request.getReviewStatus())) {
            shareTodo.setPublic(true);
        }

        ShareTodo updatedShare = shareTodoRepository.save(shareTodo);
        return convertToReviewResponse(updatedShare);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean autoReviewContent(String content) {
        // 获取所有敏感词
        List<String> sensitiveWords = sensitiveWordRepository.findAll().stream()
                .map(SensitiveWord::getWord)
                .collect(Collectors.toList());

        // 检查内容是否包含敏感词
        for (String word : sensitiveWords) {
            if (content.contains(word)) {
                return false; // 包含敏感词，审核不通过
            }
        }
        return true; // 未包含敏感词，审核通过
    }

    // 转换为响应DTO
    private ShareReviewResponse convertToReviewResponse(ShareTodo shareTodo) {
        ShareReviewResponse response = new ShareReviewResponse();
        response.setId(shareTodo.getId());
        response.setShareCode(shareTodo.getShareCode());
        response.setTodoId(shareTodo.getTodoId());
        response.setReviewStatus(shareTodo.getReviewStatus().name());
        response.setReviewComment(shareTodo.getReviewComment());
        response.setCreatedAt(shareTodo.getCreatedAt());

        // 填充待办事项内容
        Todo todo = todoRepository.findById(shareTodo.getTodoId()).orElse(null);
        if (todo != null) {
            response.setTodoContent(todo.getContent());

            // 填充用户名
            User user = userRepository.findById(todo.getUserId()).orElse(null);
            if (user != null) {
                response.setUsername(user.getUsername());
            }
        }

        return response;
    }
}
